#! /usr/bin/env python
# coding=utf8

import sys
import os
import commands
import optparse


def cprint(msg, flag=False):
    """
    带颜色的输出，
    flag:  false 为红色输出，true 为绿色输出
    """
    if flag:
        print("\033[32m"+msg+"\033[0m")
    else:
        print("\033[31m"+msg+"\033[0m")


def execmd(cmd):
    cprint(cmd, True)
    os.system(cmd)


def checkTagExists(tag, isLocal=True):
    if isLocal:
        cmd = "git tag | grep %s | wc -l" % tag
        res = commands.getoutput(cmd)
        return res.strip() != "0"
    else:
        return True


def delTag(tag, msg=""):
    if checkTagExists(tag):
        # 删除本地 tag
        rmLocalTag = "git tag -d %s" % tag
        execmd(rmLocalTag)
        # 删除远程 tag
        rmRemoteTag = "git push origin :refs/tags/%s" % tag
        execmd(rmRemoteTag)


def addTag(tag, msg):
    # 删除 tag
    delTag(tag)
    # 添加本地 tag
    addLocalTag = "git tag -a %s -m '%s'" % (tag, msg)
    execmd(addLocalTag)
    # 添加远程 tag
    addRemoteTag = "git push origin %s" % tag
    execmd(addRemoteTag)


def run(operator, dir, tag, commit):

    operatorMap = {
        "add": addTag,
        "del": delTag
    }

    dirs = dir.split(',')
    currDir = os.getcwd()

    fn = operatorMap.get(operator)
    if fn:
        cprint("----------------%s git tag--------------" %
               operator, True)

        for p in dirs:
            if not os.path.isdir(p):
                cprint("dir not exits: %" % p)
                continue
            os.chdir(p)
            fn(tag, commit)
            os.chdir(currDir)


def main():
    usage = "python %prog -o/--opeartor <operator add or del> -d/--dir <git project dir>"
    parse = optparse.OptionParser(usage)
    parse.add_option("-o", dest="operator",
                     type="string", default="add", help="opeartor type: add or del")
    parse.add_option("-m", dest="message",
                     type="string", default="", help="tag message")
    parse.add_option("-a", dest="annotate", type="string",
                     default="", help="tag name")
    parse.add_option("-d", dest="dir", type="string",
                     default=".", help="git project dir")

    options, args = parse.parse_args()

    vhallComponentDir = options.dir or os.getcwd()
    if not options.annotate:
        cprint("please input tag annotate")
        sys.exit(0)

    run(options.operator, options.dir, options.annotate, options.message)
    # print(options)


if __name__ == "__main__":
    main()
